#include "printerManager.h"

PrinterManager::PrinterManager()
{

}

QString PrinterManager::table2HTML(const QTableWidget &table, int width, bool printHiddenItem){
    QString htmlText = QString("<table width=%1 border=1 frame='border' cellspacing='0' cellpadding='3px' rules='all' style=\"font-size:10px\">").arg(width);

    if(table.horizontalHeader()->isVisible()){
        htmlText.append("<tr>");
        for(int c = 0; c < table.columnCount(); c ++){
            if(table.isColumnHidden(c) && (!printHiddenItem)){          // 是否打印隐藏内容
                continue;
            }
            QTableWidgetItem* item = table.horizontalHeaderItem(c);
            QString text = "";
            if(item){
                text = item->text();
            }
            htmlText.append(QString("<th>%1</th>").arg(text));
        }
        htmlText.append("</tr>");
    }

    // 表内容
    for(int r = 0; r < table.rowCount(); r ++){
        if(table.isRowHidden(r) && (!printHiddenItem)){             // 是否打印隐藏内容
            continue;
        }
        htmlText.append("<tr>");
        for(int c = 0; c < table.columnCount(); c ++){
            if(table.isColumnHidden(c) && (!printHiddenItem)){
                continue;
            }
            QString text = "";
            if(table.item(r, c)){
                text = table.item(r, c)->text();
            }
            htmlText.append(QString("<td>%1</td>").arg(text));
        }
        htmlText.append("</tr>");
    }
    htmlText.append("</table>");
    return htmlText;
}

void PrinterManager::printTable(const QTableWidget &table, bool printHiddenItem){

    DebugLog::funcStart(DEBUG_CONTEXT);

    QPrinter printer(QPrinter::ScreenResolution);
    QPrintDialog printDialog(&printer);

    if(printDialog.exec() != QPrintDialog::Accepted){
        return;
    }
    QTextDocument td;
    td.setHtml(table2HTML(table, printer.width()*0.62, printHiddenItem));
    td.print(&printer);

    DebugLog::funcEnd(DEBUG_CONTEXT);
}

void PrinterManager::printTable(QList<QTableWidget *> tableList, bool printHiddenItem){
    QPrinter printer(QPrinter::ScreenResolution);
    QPrintDialog printDialog(&printer);

    if(printDialog.exec() != QPrintDialog::Accepted){
        return;
    }

    QString htmlText;
    foreach(QTableWidget* table, tableList){
        htmlText.append(table2HTML(*table, printer.width()*0.62, printHiddenItem));
        htmlText.append("<p></p>");
    }
    QTextDocument td;
    td.setHtml(htmlText);
    td.print(&printer);
}
